package com.collectplus.express.app;

import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.collectplus.express.R;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.parcel.ParcelCheckActivity;
import com.collectplus.express.self.CheckQRCodeDialogActivity;
import com.collectplus.express.self.SelfBagInputActivity;
import com.zbar.camera.CameraManager;
import com.zbar.decode.CaptureActivityHandler;

import droid.frame.activity.ActivityMgr;
import droid.frame.activity.title.TitleMgr;
import droid.frame.activity.title.TitleRes;
import droid.frame.systembar.SystemBarConfig;
import droid.frame.ui.dialog.AppDialog;
import droid.frame.umeng.UMeng;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.lang.JsonParser;

/**
 * 项目中用到的扫码界面
 *
 * @author coffee<br>
 *         2015-4-1上午10:50:11
 */
public class AppCaptureActivity extends com.zbar.client.CaptureActivity implements Callback {

    private boolean isOpenFlash;
    // intent
    private String action;

    private int from;

    @Override
    public void onCreate(Bundle icicle) {
        action = getIntent().getAction();
        if (Intents.capture_station.equals(action)) {
            setLayout(R.layout.app_capture_station, true);
        } else {
            from = getIntent().getIntExtra("from", 0);
            setLayout(R.layout.order_bind, true);
        }

        if (SystemBarConfig.isSupport()) {
            // 注意需要设置FEATURE_NO_TITLE 否则适配可能会有bug
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            SystemBarConfig.showSystemStatusBar(this, R.color.app_capture_status);
        } else {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        super.onCreate(icicle);
        // 加入栈管理
        ActivityMgr.push(this);
        //
        TitleMgr titleMgr = new TitleMgr(this);
        titleMgr.initTitle();

        final ImageView rightImage = (ImageView) findViewById(R.id.title_right_image);
        titleMgr.setCommonTitle(null, new TitleRes(R.drawable.title_lampe_on, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpenFlash) {// 当前状态--亮
                    CameraManager.get().offLight();
                    rightImage.setImageResource(R.drawable.title_lampe_on);
                    isOpenFlash = false;
                } else {
                    CameraManager.get().openLight();
                    rightImage.setImageResource(R.drawable.title_lampe_off);
                    isOpenFlash = true;
                }
            }
        }));

        // 默认的
        if (action == null) {
            //查看条形码示例
            findViewById(R.id.check_qrcode_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(AppCaptureActivity.this, CheckQRCodeDialogActivity.class));
                }
            });
            TextView title = (TextView) findViewById(R.id.title_middle_text);
            title.setText("扫码绑定");
            // 手动扫码
            findViewById(R.id.capture_input).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UMeng.click(getApplicationContext(), "self_bag_code_click");
                    Intent intent = new Intent();
                    intent.setClass(AppCaptureActivity.this, SelfBagInputActivity.class);
                    // startActivityForResult(intent, 101);
                    intent.putExtra("from", 1);
                    startActivity(intent);
                    finish();
                }
            });
        }
        // 到驿站、扫码核对包裹
        else if (Intents.capture_station.equals(action)) {
            TextView title = (TextView) findViewById(R.id.title_middle_text);
            title.setText("请扫描驿站的二维码");
        }

    }

    @Override
    protected boolean callback(String contents) {
        if (Intents.capture_station.equals(action)) {
            int index = contents.lastIndexOf("=");
            String code;
            if (index > -1) {
                code = contents.substring(index + 1, contents.length());
                Intent intent = new Intent();
                intent.setClass(AppCaptureActivity.this, ParcelCheckActivity.class);
                intent.putExtra("id", code + "");// 驿站id
                startActivity(intent);
                finish();
            } else {
                code = contents;
                AppHttp.getInstance().stationGetId(code);
            }
        } else {
            Intent data = new Intent();
            data.putExtra("result", contents);
            setResult(RESULT_OK, data);
            finish();
        }
        return true;
    }

    /**
     * {@link CaptureActivityHandler#handleMessage(Message)}
     * station_get_id
     *
     * @param message
     */
    private void showMessage(String message) {
        AppDialog dialog = DialogMgr.showAppMessage(AppCaptureActivity.this, message);
        dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // 重新预览, 否则不能重新扫码
                Message message = Message.obtain(getHandler(), R.id.restart_preview);
                message.sendToTarget();
            }
        });
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 扫描二维码 获取驿站id
            case MsgID.station_get_id:
                final AppResult<?> result = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            // {"message":"success","result":{"id":3},"status":1}
                            try {
                                Object id = JsonParser.get(msg.obj + "", "result[id]");
                                if (id == null) {
                                    showMessage("未查询到驿站id");
                                    //                                    finish();
                                } else {
                                    Intent intent = new Intent();
                                    intent.setClass(AppCaptureActivity.this, ParcelCheckActivity.class);
                                    intent.putExtra("id", id + "");// 驿站id
                                    startActivity(intent);
                                    finish();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            // Alert.toast(result.getMessage());
                            showMessage(result.getMessage());
                        }
                    }
                });
                return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmUtils.hide(this);
        //
        ActivityMgr.remove(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101 && resultCode == RESULT_OK) {
            setResult(RESULT_OK, data);
            finish();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

}
